package com.zhenwei.zscm.repo;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhenwei.zscm.common.utils.Linq;
import com.zhenwei.zscm.entity.FileEntity;
import com.zhenwei.zscm.mapper.IFileMapper;
import com.zhenwei.zscm.mappings.FileMapping;
import com.zhenwei.zscm.model.dto.file.FileDTO;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@AllArgsConstructor
public class FileRepo extends ServiceImpl<IFileMapper, FileEntity> {

    @Transactional(rollbackFor = Exception.class)
    public boolean Save(List<FileDTO> list) {
        list.forEach(dto -> {
            dto.setGuid(IdUtil.simpleUUID());
        });
        List<FileEntity> entityList = Linq.mapList(list, FileMapping.INSTANCE::dto2Entity);
        return this.saveBatch(entityList);
    }
    public boolean Save(FileDTO dto) {
        dto.setGuid(IdUtil.simpleUUID());
        FileEntity e = FileMapping.INSTANCE.dto2Entity(dto);
        return this.save(e);
    }
    public List<FileDTO> getList(List<String> fileIds) {
        var q = new LambdaQueryWrapper<FileEntity>()
                .in(FileEntity::getGuid, fileIds)
                .eq(FileEntity::getDeleted, false)
                .orderByAsc(FileEntity::getId);
        var list = this.list(q);
        return Linq.mapList(list, FileMapping.INSTANCE::entity2Dto);
    }

    public FileDTO getOne(String fileId) {
        var q = new LambdaQueryWrapper<FileEntity>()
                .eq(FileEntity::getGuid, fileId)
                .eq(FileEntity::getDeleted, false);
        var list = this.list(q);
        return Linq.getFirst(list, FileMapping.INSTANCE::entity2Dto);
    }

    public List<FileDTO> getUnusedFiles(){
        var q = new LambdaQueryWrapper<FileEntity>()
                .eq(FileEntity::getDeleted, true);
        var list = this.list(q);
        return Linq.mapList(list, FileMapping.INSTANCE::entity2Dto);
    }

    public List<FileDTO> getUnrelatedFiles(){
        return baseMapper.getUnrelatedFiles();
    }

    public void remove(String fileId) {
        var q = new LambdaQueryWrapper<FileEntity>()
                .eq(FileEntity::getGuid, fileId)
                .eq(FileEntity::getDeleted, false);
        this.remove(q);
    }
}
